# coding: utf-8
import datetime
import os
import threading
from threading import Thread
from time import sleep

CONTROL_SERIAL_NUMBER_LINK = "http://127.0.0.1:8000/control/serial_number"


class Singleton(object):
    """单例模式"""
    _instance_lock = threading.Lock()

    def __new__(cls, *args, **kwargs):
        if not hasattr(cls, "_instance"):
            with cls._instance_lock:
                if not hasattr(cls, "_instance"):
                    impl = cls.configure() if hasattr(cls, "configure") else cls
                    instance = super(Singleton, cls).__new__(impl, *args, **kwargs)
                    instance.__init__(*args, **kwargs)
                    cls._instance = instance
        return cls._instance


class SingleDict(Singleton):
    """
    单例字典, 用来存放流水号
    """
    snd = {}

    def get_or_append(self, flag):
        """
        获取或者添加时间戳到time_list里
        如果获取到return True
        如果没获取return False
        :param flag:
        :return:
        """
        if self.snd.get(flag):
            return True
        else:
            now_time = datetime.datetime.now()
            after_30_second = now_time + datetime.timedelta(seconds=30)
            self.snd[flag] = after_30_second
            return False

    def del_flag(self, flag):
        if self.snd.get(flag):
            del self.snd[flag]


def check_single_dict_time():
    """
    检查 信号字典
    :return:
    """
    sd = SingleDict()
    now_time = datetime.datetime.now()
    while True:
        for k, v in sd.snd.items():
            if now_time >= v:
                del sd.snd[k]
                print('serial_number:%s, timeout, is deleted!' % k)
        sleep(1)


base_path = os.path.dirname(os.path.abspath(__file__))

if os.path.exists(base_path + "/flag"):
    t = Thread(target=check_single_dict_time)
    t.setDaemon(True)
    t.start()
    print('start control serial number!')
    os.remove(base_path + "/flag")
else:
    file = open(base_path + "/flag", "w")
    file.close()


class IpList:
    ip_list = []

    @classmethod
    def add_ip(cls, ip):
        if ip not in cls.ip_list:
            cls.ip_list.append(ip)
        print (cls.ip_list)